package com.qianbei.view.transport;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.Carbean;
import com.qianbei.bean.GetCarbean;
import com.qianbei.bean.GetEmpty_Body;
import com.qianbei.bean.GetNamebean;
import com.qianbei.common.base.ActivityManagers;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.util.TextUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NameActivity extends BaseActivity {

    String customid;

    @Bind(R.id.reSign)
    TextView resign;
    String NAME;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        SignatureCardView view = new SignatureCardView(this);
        setContentView(R.layout.name_activity);
        ButterKnife.bind(this);
        setTitle("客户签名");
        mTitle.setrightTitle("保存");

        customid = getIntent().getStringExtra("id");

        sp = getSharedPreferences(TextUtil.shhc_gfwl_sp, Context.MODE_PRIVATE);
    }

    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                showD();
                break;

            default:
                break;
        }

    }
    private String msgSp;

    /**
     * 提示用户 完成签名
     */
    public void showD() {
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                .setMessage("是否确认签名？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        GetandSaveCurrentImage();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    /**
     * 清空画布
     */
    @OnClick(R.id.reSign)
    public void restore() {
        Log.d("ReSign", "reSign");
        SignatureCardView view = (SignatureCardView) findViewById(R.id.signatureView);
        view.repaint();
    }

    /**
     * encodeBase64File:(将文件转成base64 字符串). <br/>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    /**
     * 上传图片 的接口
     *
     * @param imageUri
     */
    public void upImage(String imageUri) {
        Map<String, File> fileParams = new HashMap<>();
        File file = new File(imageUri);
        fileParams.put("file", file);
        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
            //TODO 需要对无网情况图片上传做处理
//            NAME = imageUri.substring(imageUri.lastIndexOf("/")+1,imageUri.length());
            NAME = imageUri;
            try {
                select(encodeBase64File(imageUri).replaceAll("[\\s*\t\n\r]", ""));

            } catch (Exception e) {
                new MsgAlert().show("转换base64异常");
                e.printStackTrace();
            }
        } else {
            ServerControl sc = new ServerControl(fileParams);
            //获取本地的
            msgSp = "\n签名提交:" + TextUtil.getCurTime()
                    + "\nUrl:" + sc.getUrlImg() + "\n参数:" + imageUri;
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        String ID = sr.bodyData.optString("message");
                        select(ID);
                        new MsgAlert().show("上传成功，请保存提交");
                    }

                    //保存到sp
                    msgSp = msgSp + "\n\n签名提交返回:" + TextUtil.getCurTime() +
                            "\n" + sr.toString() + "\n-----------------------------------------------------------\n"
                            + sp.getString(TextUtil.commitKey, "");
                    sp.edit().putString(TextUtil.commitKey, msgSp).commit();

                }
            };
            new ProgressDialog(mContext).startControlUPpic(sc);
        }
    }


    /**
     * 上传 图片 img custom uid
     *
     * @param imgId
     */
    private void select(String imgId) {
        ArrayList<String> photo_ids = new ArrayList<>();
        ArrayList<String> photo_names = new ArrayList<>();
        photo_names.add(NAME);
        changeCacheStatus(customid);
        if (imgId.length() > 50) {//没用网络 缓存数据到内存
            photo_ids.add("");
            RequeastBean bean =
                    new RequeastBean("sign", "com.cygps.dubbo.WasteTransport.IRouteInfo",
                            new GetNamebean(customid, photo_ids, photo_names));
//            MyApplication.netList.add(bean); bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetNamebean.class.getName());
            requestPersistent.setType("1");
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            ActivityManagers.getInstance().popTo(TransportfActivity.class);
            finish();
        } else {
            photo_ids.add(imgId);
            RequeastBean bean =
                    new RequeastBean("sign", "com.cygps.dubbo.WasteTransport.IRouteInfo",
                            new GetNamebean(customid, photo_ids));
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        ActivityManagers.getInstance().popTo(TransportfActivity.class);
                        finish();
                    }

                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }


    /**
     * 获取和保存当前屏幕的截图
     */
    private void GetandSaveCurrentImage() {
        //1.构建Bitmap
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();

        Bitmap Bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();

        String SavePath = getSDCardPath() + "/qianbei/ScreenImage";

        //3.保存Bitmap
        try {
            File path = new File(SavePath);
            //文件
            String filepath = SavePath + "/Screen_1.png";
            File file = new File(filepath);
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                upImage(filepath);
                Toast.makeText(mContext, "截屏文件已保存至SDCard/qianbei/ScreenImage/下", Toast.LENGTH_LONG).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getSDCardPath() {
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdcardExist) {
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }

    /**
     * 更新缓存中指定客户的收运状态
     *
     * @param customerId
     */
    private void changeCacheStatus(String customerId) {
        String jsonString = SetData.getJobs();
        com.alibaba.fastjson.JSONArray jobsAry = JSON.parseArray(jsonString);
        String jobId = SetData.getJobid();

        for (int i = 0; i < jobsAry.size(); i++) {
            com.alibaba.fastjson.JSONObject oneJob = jobsAry.getJSONObject(i);
            String dataJobId = oneJob.getString("_id");
            if (dataJobId.equals(jobId)) {
                com.alibaba.fastjson.JSONArray cusAry = oneJob.getJSONArray("customerAry");
                for (int j = 0; j < cusAry.size(); j++) {
                    com.alibaba.fastjson.JSONObject oneCus = cusAry.getJSONObject(j);
                    String cusId = oneCus.getString("id");
                    if (cusId.equals(customerId)) {
                        String oldStatus = oneCus.getString("status");
                        if (oldStatus.equals("1")) {
                            oneCus.put("status", "2");//2 完成收运
                            SetData.setJobs(jobsAry.toJSONString());
                        }
                        break;
                    }
                }
                break;
            }
        }
    }

}
